
#ifndef _B5M_INI_H_
#define _B5M_INI_H_

#include "common.h"
#include <map>
#include <string>

B5M_BEGIN_VERSIONED_NAMESPACE_DECL

#define BUFFER_SIZE 5000
#define NEWLINE_UNKNOWN 0  /* Newline convention in file is unknown */
#define NEWLINE_UNIX    1  /* Newline convention in file is '\n'   (ASCII 10) */
#define NEWLINE_DOS     2  /* Newline convention in file is '\r\n' (ASCII 13,10) */
#define NEWLINE_MAC     3  /* Newline convention in file is '\r'   (ASCII 13) */

/** Calculates the number of elements in an array, using sizeof. */
#define SZ(X)  (sizeof(X) / sizeof(*X))

template <class T = EncodeBase>
class INI
{
public:
	typedef char char_t;

	///Type definitions
	typedef std::map<std::string, std::string> keys_t;
	typedef std::map<std::string, keys_t*> sections_t;

	typedef keys_t::iterator keysit_t;
	typedef sections_t::iterator sectionsit_t;

	typedef std::pair<std::string, std::string> keyspair_t;
	typedef std::pair<std::string, keys_t*> sectionspair_t;

	///Data members
	keys_t* current;
	sections_t sections;

	///Constuctor/Destructor
	INI();
	INI(std::string filePath, bool parse = true);

	~INI();

	///Accessing structure
	keys_t& operator[](std::string section);

	bool Create(const std::string section);

	bool Select(const std::string section);

	//Set
	bool Set(const std::string key, const std::string value);

	std::string Get(const std::string key,const std::string def);  //Can handle const char* without casting

	///Functions
	bool Parse(std::string filePath = "");

	bool IsParsed() {return _parsed_success;};

	void Clear();

	void Save(std::string filePath = "");

	const std::string& GetFileName() const { return m_filePath; };

private:

	bool ParseContent(std::string& content);

	std::string m_filePath;

	bool _parsed_success;

	///Output
	char *chomp(char *string);
	int simple_read_line(const char* content,unsigned long *index,char **dest, int *newline);
	std::string makeSection(const std::string& section);
	std::string makeKeyValue(const std::string& key, const std::string& value);
};

B5M_END_VERSIONED_NAMESPACE_DECL

#include "INI_T.h"

#endif